<?php
namespace app\admin\controller;
use think\Db;
class Role extends Common{
	public function index(){

		$data = model('Role')->getAllData(1);
		// $rule_id = implode(',',$data[0]['rule_id']);
		
		$this->assign("data",$data);
		return $this->fetch();

	}
	 //软删除
    public function del(){
    	//获取的是一个数组
    	$ids = input('post.ids/a');
    	//将数组转为字符串 以逗号分隔
    	$ids = implode(',',$ids);
    	//软删除 更新状态
    	$result = Db::name('role')->where("id in ($ids)")->setField('status',0);
    	if($result){
    		$this->success("删除成功");
    	}else{
    		$this->error("删除失败");
    	}
    }

    //添加角色
    public function add(){
    	if(request()->isPost()){

	    		$data = input('post.data/a');
	    		
	    		// dump($data);die;
	    		if(!$data){
	    			return json(array('code'=>0,'msg'=>"参数错误"));
	    		}
	    		
	    		$rule_id = implode(',',$data['rule_id']);
	    		// dump($rule_id);die;
				$role_id = model('Role')->addRole($data);
				if (!$role_id) {
	    			return json(array('code'=>0,'msg'=>"添加失败"));
	    		}

				$data = ['role_id'=>$role_id,'rule_id'=>$rule_id];
				$result = Db::name('role_rule')->insert($data);
	    		if($result){
	    			return json(['code'=>1,'msg'=>'添加成功']);
	    		}else{
	    			return json(['code'=>0,'msg'=>'添加失败']);
	    		}

    	}else{

			$rule = Db::name('rule')->where("parent_id",0)->select();
			$rule1 = Db::name('rule')->select();
			
			$this->assign('rule',$rule);
			$this->assign('rule1',$rule1);
	    	
	    	return $this->fetch();
    	}
    	
    }

    public function edit($id = null){
        // dump($id);die;
        if(request()->isPost() && $id != null){
            $data = input('post.data/a');
            $data['id'] = $id;
            $data['status'] = 1;
            $data['add_time'] = date("Y-m-d H:i:s");
            // dump($data);die;
            $rules = implode(',',$data['rule_id']);
            unset($data['rule_id']);
            $result = model('Role')->RoleEdit($data,$rules);
            if(!$result){
                return json(array('code'=>0,'msg'=>'未修改'));
            }else{
                return json(array('code'=>1,'msg'=>'修改成功！'));
            }
        }else{
            $info = model('Role')->findRole($id);
            $data = model('Role')->getAllRule();
            $rule_id = explode(",",$info['rule_id']);
            // dump($rule_id);die;
            $this->assign('rule_id',$rule_id);
            $this->assign('info',$info);
            $this->assign('data',$data);
            return $this->fetch();
        }
    }

}